﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using Microsoft.Phone.Net.NetworkInformation;
using Store.WP7.Data;
using Store.WP7.Data.WebStore;
using Store.WP7.Framework;
using Store.WP7.Framework.ErrorManagement;
using Store.WP7.Framework.Settings;

namespace Store.WP7.ViewModels
{
    public class OrdersViewModel : PageViewModelBase
    {
        #region Private Fields

        private readonly StoreService _storeService;
        private readonly AppSettings _appSettings;

        #endregion

        #region Ctors

        public OrdersViewModel()
        {
            _storeService = new StoreService();
            _appSettings = AppSettings.Load();
        }

        #endregion

        #region Public Properties

        private readonly ObservableCollection<OrderViewModel> _orders = new ObservableCollection<OrderViewModel>();
        /// <summary>
        /// Gets all user's orders
        /// </summary>
        public ObservableCollection<OrderViewModel> Orders
        {
            get
            {
                return _orders;
            }
        }

        private OrderViewModel _selectedOrder;
        /// <summary>
        /// Selected order
        /// </summary>
        public OrderViewModel SelectedOrder
        {
            get { return _selectedOrder; }
            set
            {
                _selectedOrder = value;
                RaisePropertyChanged(() => SelectedOrder);

                OnOrdersSelectionChanged();
            }
        }

        #endregion

        #region Public Methods

        public void OnOrdersSelectionChanged()
        {
            if (SelectedOrder != null)
            {
                NavigationService.Navigate(new System.Uri(string.Format("/Views/OrderDetailsPage.xaml?orderId={0}", SelectedOrder.Id), System.UriKind.Relative));
                // To unselect the item from the list
                SelectedOrder = null;
            }
        }

        public override void OnLoaded()
        {
            base.OnLoaded();

            LoadOrders();
        }

        #endregion

        #region Private Methods

        private void LoadOrders()
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                #region

                int customerId = _appSettings.CustomerId;

                _storeService.LoadOrdersAsync(customerId, serviceResult =>
                {
                    if (serviceResult.Error == null)
                    {
                        var orders = serviceResult.Result;
                        CacheManager.Current.Add(AppSettingsKeyNames.OrdersPage, orders, TimeSpan.FromMinutes(15));

                        Deployment.Current.Dispatcher.BeginInvoke(() => Orders.Clear());

                        foreach (var order in orders)
                        {
                            var orderViewModel = new OrderViewModel(order);
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                Orders.Add(orderViewModel);
                            });
                            Thread.Sleep(20);
                        }

                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            BusyMessage = "";
                            IsBusy = false;
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            IsBusy = false;
                            ErrorManager.HandleError(ErrorType.WebServiceCallbackFail, serviceResult.Error);
                        });
                    }
                });

                #endregion
            }
            else
            {
                var ordersPage = CacheManager.Current.Get<List<Order>>(AppSettingsKeyNames.OrdersPage);

                if (ordersPage != null)
                {
                    foreach (var order in ordersPage)
                    {
                        var orderViewModel = new OrderViewModel(order);
                        Deployment.Current.Dispatcher.BeginInvoke(() => {
                            Orders.Add(orderViewModel);
                        });
                        Thread.Sleep(20);
                    }
                    BusyMessage = "";
                    IsBusy  = false;
                }
            }
        }

        #endregion
    }
}
